<?php
    if (!isset($_POST["url"])) {
?>    
    <html>
	<head>
	</head>
	<body>
		<form action="index.php" method="post">
			url:
			<input name="url" id="url" size="25" maxlength="200" type="text" value="">
			<br>
			<input name="submit" value="MySpace Seite auslesen" type="submit">
		</form>
    </body>
    </html>
<?
    } elseif(isset($_POST["url"]) && !isset($_POST["id"])) {
?>
    <html>
	<head>
	</head>
	<body>
<?
        $result = get_dl_link($_POST["url"]);

        if($result['result']) {
        echo $result['artist'];
?>

        <form action="index.php" method="post">
            <input type="hidden" name="url" value="<? echo $_POST['url']; ?>">
            <br>
            Trackauswahl: <br><br>
<?
            foreach($result['tracks'] as $track)
                echo "<input type=\"radio\" name=\"id\" value=\"". $track['id'] ."\">". $track['name'] ."<br>";
   

?>
			<input name="submit" value="Download starten" type="submit">
		</form>
<?
    } else {
        echo "Es ist ein Fehler aufgetreten";
    }
?>
    </body>
    </html>
<?
    } elseif(isset($_POST["url"]) && isset($_POST["id"])) {
        get_dl_link($_POST["url"], $_POST["id"]);
    }
    
    function get_dl_link($url, $id='') {
    
        $result = array();
    
        if (stristr($url,"http://") && stristr ($url,"myspace.com/")) {
    		$file = file($url);
    		$profile = '';
    		for ($i=0; $i<count($file); $i++) {
    			$profile .= trim($file[$i]);
    		}
    		preg_match_all("|MySpace.ClientContext = {\"UserId\":-1,\"DisplayFriendId\":(.*),\"IsLoggedIn\":|siU",$profile,$friendid);
    		$site = "http://mediaservices.myspace.com/services/media/musicplayerxml.ashx?b=".$friendid[1][0];
            $site = file_get_contents($site,'r');
    		$site = eregi_replace("/std_", "/full_", $site);
    		preg_match_all("|durl=\"(.*)\"|siU",$site,$links);
    		preg_match_all("|title=\"(.*)\"|siU",$site,$titles);
            
            preg_match_all("|MySpace.com\s-\s(.*)\s-\s.*,|siU",$profile,$name);
            $name=$name[1][0];
            $result['artist']=$name;

 
            for($i=0 ; isset($links[1][$i]) ; $i++) {
                if(!$id) {
                    $result['tracks'][$i]['id'] = $i;
                    $result['tracks'][$i]['name'] = $titles[1][$i];                    
                } elseif ($id && $id == $i) {
                    header("Content-Disposition: attachment; filename=\"". $name ." - ". $titles[1][$i] .".mp3\""); 
                    readfile($links[1][$i]);
                }
    		}
            $result['result'] = $i ? 1 : 0;
    	} else {
            $result['result'] = 0;
        }
        
        return $result;
    }
    
?>